package com.atguigu.gmall.auth.controller;

import com.atguigu.gmall.auth.service.AuthService;
import com.atguigu.gmall.common.utils.JwtUtils;
import com.atguigu.gmall.common.utils.MyURLUtils;
import com.atguigu.gmall.common.utils.RsaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PrivateKey;
import java.util.HashMap;

@Controller
@RequestMapping("/")
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * 首页跳转到登录页面
     * http://www.gamll.com/toLogin?returnUrl=www.gmall.com
     */
    @RequestMapping("toLogin")
    public String toLogin(@RequestParam(value = "redirect_url", required = false) String returnUrl, Model model) {
        model.addAttribute("returnUrl", returnUrl);
        return "login";
    }


    /**
     * 点击登录页面的登录按钮访问该方法
     * 对登录信息进行校验
     * 生成token,
     * 存入cookie,
     * 重定向到之前的页面
     */
    @PostMapping("login")//前端用的post表单提交的数据，post请求接收
    public String login(@RequestParam("returnUrl") String returnUrl,
                        @RequestParam("loginName") String loginName,
                        @RequestParam("password") String password,
                        HttpServletRequest request,
                        HttpServletResponse response) {
        try {
            authService.login(loginName, password, request, response);
            return "redirect:" + MyURLUtils.myUrlEncode(returnUrl);//登录成功返回之前的页面
        } catch (Exception e) {
            return "login";//登录失败返回登录页面
        }
    }


}
